package com.anmingle.pswb.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.anmingle.common.R;
import com.anmingle.common.ResponseResult;
import com.anmingle.enums.ErrorCode;
import com.anmingle.exception.BusinessException;
import com.anmingle.pswb.model.entity.User;
import com.anmingle.pswb.service.UserService;
import com.anmingle.pswb.service.impl.UserServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

import static com.anmingle.utils.RequestUtils.GET;
import static com.anmingle.utils.RequestUtils.Post;


/**
 * @author anmingle
 * @date 2022/5/30 16:08
 */
@RestController
@RequestMapping("/wx")
@Slf4j
public class WxController {

    @Resource
    private UserService userService;

    /**
     * appid
     */
    private static final String appid = "wxcfd22e94b028a648";

    /**
     * 密钥
     */
    private static final String secret = "b38860b6ded9f1d4cc5c7322d21ee176";

    @GetMapping("/getOpenid")
    public ResponseResult getOpenid(String code) {

        if (StringUtils.isAllBlank(code)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "code为空");
        }
        //微信官方提供获取openid的url
        String WX_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
        //替换appid，appsecret，和code
        String requestUrl = WX_URL.replace("APPID", appid).
                replace("SECRET", secret).replace("JSCODE", code).
                replace("authorization_code", "authorization_code");
        //定义json对象
        JSONObject convertvalue = new JSONObject();
        //调用get方法
        String returnvalue = GET(requestUrl);
        //解析返回值，对象解析成字符串
        convertvalue = (JSONObject) JSON.parse(returnvalue);
        String sessionKey = (String) convertvalue.get("session_key");
        String openid = (String) convertvalue.get("openid");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(openid), "openid", openid);
        //.eq(StringUtils.isNotBlank(sessionKey),"session",sessionKey);
        User user1 = userService.getOne(queryWrapper);
        if (user1 == null) {
            User user = new User();
            user.setOpenid(openid);
            user.setSession(sessionKey);

            userService.save(user);
        } else if (user1.getName() != null || user1.getPassword() != null) {
            /**
             * 微信小程序用户只要有账号密码就无需登录
             */
            Map<String, Object> map = UserServiceImpl.ReturnUserResponse(user1);

            map.put("openid", openid);
            map.put("session", sessionKey);
            return R.ok("登录成功", map);
        }
        User one = userService.getOne(queryWrapper);

        return R.ok(one);
    }

    /**
     * 由于微信要收钱 暂不提供此服务
     * @param code
     * @return
     */
    @GetMapping("/getPhone")
    public ResponseResult<String> getPhone(String code) {

        if (StringUtils.isAllBlank(code)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "code为空");
        }

        String phone = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKE";
        String access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
        JSONObject jsonObject = new JSONObject();

        String accessUrl = access_token.replace("APPID", appid)
                .replace("APPSECRET", secret);
        String accessToken = GET(accessUrl);

        jsonObject = (JSONObject) JSON.parse(accessToken);
        System.out.println(jsonObject.toString());


        String acc = (String) jsonObject.get("access_token");


        String message = "{'code':'" + code + "'}";
        String getPhone = phone.replace("ACCESS_TOKE", acc);
        JSONObject parseObject = JSONObject.parseObject(message);

        String post = Post(getPhone, parseObject);

        return R.ok(post);
    }


}

